package com.db.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;

public class DBUtil {
	private static DataSource ds;
	private static String url = "jdbc:mysql://localhost:3306/teyoujia?useUnicode=true&characterEncoding=utf-8";
	public static Connection getConnection() throws Exception
	{
		//Log.debug(DBUtil.class,"getConnection() invoked!!!");
		try {
			if(ds == null){
				ds = setupDataSource(url);
			}
			return ds.getConnection();
		} catch(Exception e) {
			//Log.debug(DBUtil.class,"getConnection error:" + e.getMessage());
			throw e;
		}
	}
	 public static DataSource setupDataSource(String connectURI) {   
		    
	        BasicDataSource ds = new BasicDataSource();   
	        ds.setDriverClassName("com.mysql.jdbc.Driver");   
	        ds.setUsername("root");   
	        ds.setPassword("123");   
	        ds.setUrl(connectURI);   
	        ds.setMaxActive(20);
	        ds.setMaxIdle(10);
	        ds.setMaxWait(10000);
	       // Log.debug(DBUtil.class,"DB initialization invoked!!!");
	        return ds;   
	  
	    }   

	/**
	 * close connection
	 */
	public static void closeConnection(Connection con)
	{
		//Log.debug(DBUtil.class,"closeConnection");
		try {
			if(con != null)
				con.close();
		} catch(Exception e) {
			//Log.error(DBUtil.class,"closeConnection error: " + e.getMessage());
		}
	}
	
	/**
	 * close ResultSet,PreparedStatement,Connection
	 */
	public static void closeAll(ResultSet rs, PreparedStatement ps,Connection con) {
		//Log.debug(DBUtil.class,"closeAll");
		try {
			if(rs != null)
				rs.close();
			if(ps != null)
				ps.close();
			if(con != null)
				con.close();
		} catch(Exception e) {
			//Log.error(DBUtil.class, "closeAll error : " + e.getMessage());
		}
	}
	
	public static int getLastInsertId(Connection conn) throws Exception{
		PreparedStatement ps = conn.prepareStatement("select  LAST_INSERT_ID()");
		ResultSet rs = ps.executeQuery();
		if(rs.next()){
			return rs.getInt(1);
		}
		closeAll(rs,ps,null);
		return -1;
		
	}
}
